$(function () {
    init();
    var spring = 40;
    function init() {
        $("ul").width($("li").length * $("li").width());
        $("li").click(function () {
            $(this).addClass("active").siblings().removeClass("active");
            var index = $(this).index();
            var dis = - $("li").width() * index;
            var leftDis = $("div").width() - $("ul").width();
            if (dis <= leftDis) {
                dis = leftDis;
            }
            $("ul").css("transition", "all .5s");
            $("ul").css("transform", "translateX(" + (dis) + "px)");

        });
        swiper()
    }


    /* 1 实现了单次拖拽*/
    /* 2 加上alrDis实现了记住上次位置 多次拖拽*/
    /* 3 加上spring 实现了弹簧距离 */
    /* 4 加上点击移动li标签*/
    /* 5 加上过渡结束事件*/
    function swiper() {
        /* 拖拽开始的起点 */
        var startX = 0;
        /* 已经移动的距离 */
        var alrDis = 0;
        /* 弹簧的距离*/

        $("ul").on("touchstart", function (e) {
            /*jq touchstart 获取坐标*/
            var _touch = e.originalEvent.targetTouches[0];
            startX = _touch.pageX;
        });
        $("ul").on("touchmove", function (e) {
            var _touch = e.originalEvent.targetTouches[0];
            var dis = _touch.pageX - startX;
            dis = dis + alrDis;
            if (dis >= spring) {
                dis = spring;
            }
            var leftDis = $("div").width() - $("ul").width() - spring;
            if (dis <= leftDis) {
                dis = leftDis;
            }
            // console.log(dis);.
            $("ul").css("transition", "none");
            $("ul").css("transform", "translateX(" + dis + "px)");
        });
        $("ul").on("touchend", function (e) {
            var _touch = e.originalEvent.changedTouches[0];
            alrDis = _touch.pageX - startX + alrDis;

            if (alrDis > 0) {
                $("ul").css("transition", "all .5s");
                $("ul").css("transform", "translateX(" + 0 + "px)");
                alrDis = 0;
            }

            var leftDis = $("div").width() - $("ul").width() - spring;
            if (alrDis < leftDis) {
                $("ul").css("transition", "all .5s");
                $("ul").css("transform", "translateX(" + (leftDis + spring) + "px)");
                alrDis = leftDis + spring;
            }
            // console.log(alrDis);
        });
        $("ul").on("transitionEnd", function () {
            $("ul").css("transition", "none");
        })
    }
})